import IPairTxData from '~/models/IData'
import IPlugin from './IPlugin'
import axios from 'axios'
import config from '~/config'

let txToFromMap = new Map<string, string>()
export default class SellAccountAdjustPlugin implements IPlugin {

    name = 'SellAccountAdjust'

    async modData(data: IPairTxData) {
        const swaps = data.swaps
        const UNISWAP_ROUTER_V2 = config.contract.router

        let txIdList: string[] = []
        let taskList: Promise<any>[] = []
        for (let i = 0; i < swaps.length; i++) {

            const txId = swaps[i].transaction.id

            // skip buy tx
            if (swaps[i].account !== UNISWAP_ROUTER_V2) {
                continue
            }
            // skip exist
            if (txToFromMap.get(txId) !== undefined) {
                continue
            }
            // query every sell accounts
            const task = axios.get(`${config.base1}isBlack?tx_hash=${txId}`)
            txIdList.push(txId)
            taskList.push(task)
        }

        // await all query & set txToFromMap
        let reses = await Promise.all(taskList);
        for (let i = 0; i < taskList.length; i++) {
            txToFromMap.set(txIdList[i], reses[i].data.data.tx_from.toLowerCase())
        }

        // replace account of sell tx
        for (let i = 0; i < swaps.length; i++) {
            const txId = swaps[i].transaction.id
            if (swaps[i].account === UNISWAP_ROUTER_V2) {
                swaps[i].account = txToFromMap.get(txId)
            }
        }
        return data
    }
}